/**
 * @fileOverview process add edge
 * @author huangtonger@aliyun.com
 */

const Page = require('../../base/');
const Util = require('../util');
const Global = require('../global');

Page.registerBehaviour('processAddEdge', diagram => {
  const graph = diagram.getGraph();
  graph.behaviourOn('mousemove', ev => {
    const addEdgeConfig = diagram.get('addEdgeConfig');
    if (!addEdgeConfig) {
      return;
    }
    const { addModel, delegation, startPoint, sourceItem } = addEdgeConfig;
    if (!delegation) {
      return;
    }
    Util.dragingEdgeEndPoint({
      endPointType: 'target',
      edgeModel: addModel,
      graph,
      delegation,
      startPoint,
      ev,
      sourceItem
    });
  });
  graph.behaviourOn('mouseup', ev => {
    const addEdgeConfig = diagram.get('addEdgeConfig');
    if (!addEdgeConfig) {
      return;
    }
    const { addModel, delegation, sourceItem } = addEdgeConfig;
    const editor = diagram.editor;

    if (!delegation) {
      resetStatus();
      return;
    }
    const nodes = graph.getNodes();
    nodes.forEach(node => {
      diagram.clearAnchor(node);
    });
    diagram.clearAnchor(sourceItem);
    diagram.setActived(sourceItem, false);
    diagram.setSelected(sourceItem, false);
    diagram.css({
      cursor: Global.cursor.beforePanCanvas
    });
    delegation.remove();
    const isChange = Util.dropUpdateEdge({ ev, endPointType: 'target', model: addModel, diagram });
    if (isChange) {
      if (editor) {
        editor.executeCommand('add', {
          type: 'edge',
          addModel
        });
      } else {
        graph.add('edge', addModel);
      }
    }
    graph.draw();
    diagram.endAdd();
    resetStatus();
  });
  graph.behaviourOn('canvas:mouseleave', () => {
    const addEdgeConfig = diagram.get('addEdgeConfig');
    if (!addEdgeConfig) {
      return;
    }
    const { delegation, sourceItem } = addEdgeConfig;
    if (!delegation) {
      resetStatus();
      return;
    }
    const nodes = graph.getNodes();
    nodes.forEach(node => {
      diagram.clearAnchor(node);
    });
    diagram.setActived(sourceItem, false);
    diagram.clearAnchor(sourceItem);
    delegation.remove();
    diagram.cancelAdd();
    graph.draw();
    resetStatus();
  });
  function resetStatus() {
    diagram.setSignal('dragEdge', false);
    diagram.set('addEdgeConfig', {
      addModel: undefined,
      delegation: undefined,
      startPoint: undefined,
      sourceItem: undefined
    });
  }
});
